import html2canvas from 'html2canvas'
export function saveShare(options: any = { domId: '', fileName: new Date() }) {
  return new Promise((resolve, reject) => {
    if (!options.domId) {
      alert('生成图片的元素不存在')
      reject()
    }
    const imageDom = document.getElementById(options.domId)
    const clientWidth = imageDom.offsetWidth //获取容易的宽高
    const clientHeight = imageDom.offsetHeight
    let canvas = document.createElement('canvas') //创建Canvas对象
    var scale = 2 //用于渲染的比例。默认为浏览器设备像素比率
    canvas.width = clientWidth * scale
    canvas.height = clientHeight * scale
    const ops = {
      scale: scale,
      width: clientWidth, //画布的宽度
      height: clientHeight, //画布的高度
      // 跨域配置
      useCORS: true, // 使用跨域
      allowTaint: true, // 允许使用跨域资源
      tainTest: false,
      backgroundColor: null,
    }
    html2canvas(imageDom, ops).then((canvas) => {
      // 转成图片，生成图片地址
      const imgUrl = canvas.toDataURL('image/png')
      resolve(imgUrl)
    }).catch(() => {
      reject()
    })
  })
}

export function download(imgUrl, kh, fileName) {
  return new Promise((resolve, reject) => {
    getUrlBase64(imgUrl, kh)
      .then((base64) => {
        const link = document.createElement('a')
        link.href = base64
        link.download = `${fileName}.png`
        link.click()
        resolve()
      })
      .catch(() => {
        reject()
      })
  })
}

export function getUrlBase64(url, kh) {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.crossOrigin = 'Anonymous' // 允许跨域
    img.src = url
    img.onload = () => {
      // eslint-disable-next-line prefer-destructuring
      canvas.height = kh[1]
      // eslint-disable-next-line prefer-destructuring
      canvas.width = kh[0]
      ctx.drawImage(img, 0, 0, kh[0], kh[1])
      const dataURL = canvas.toDataURL('image/png')
      canvas = null
      resolve(dataURL)
    }
    img.onerror = () => {
      reject()
    }
  })
}
